package com.juyu.miliao.common.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletTool {

	public static String params2Str(HttpServletRequest request){
		return params2Str(request.getParameterMap());
	} 
	
	public static String params2Str(Map<String, String[]> map){
		if(map.size()>0){
			StringBuilder builder = new StringBuilder();
			for(Map.Entry<String, String[]> entry:map.entrySet()){
				builder.append(entry.getKey()).append("=").append(entry.getValue()[0]).append("&");
			}
			return builder.toString();
		}
		return "";
	}
	
	public static String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		request.getRemoteHost();
		String ipstr = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
		ipstr = getIp(ipstr);
		return ipstr;
	}

	private static String getIp(String pString) {
		String regexString = ".*(\\d{3}(\\.\\d{1,3}){3}).*";
		String regexString2 = ".*(\\d{2}(\\.\\d{1,3}){3}).*";
		String IPString = pString.replaceAll(regexString, "$1");
		if (IPString.indexOf(".") > 3)
			IPString = pString.replaceAll(regexString2, "$1");
		return IPString;
	}
	
	public static void writeJSONStr(HttpServletResponse response, String jsonStr) throws IOException{
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		pw.print(jsonStr);
		pw.flush();
		pw.close();
	}
	
}
